<template>
	<view class="content" v-if="isWeixin">
		<view class="title">
			<image src="@/static/img/logo.png" alt=""></image>
			<view class="title-rt">
				<h3>金米云付</h3>
				<p>加油站助手</p>
			</view>
		</view>
		<view class="form-input">
			<van-form validate-trigger="onBlur" @submit="gologin">
				<van-cell-group inset class="input-box">
					<!-- <van-field v-model="formdata.userName" name="userName" label="手机号" placeholder="请输入手机号" :rules="rulesName"
						type="tel" maxlength="11" /> -->
					<van-field v-model="formdata.userName" name="userName" label="手机号" placeholder="请输入手机号" maxlength="11" />
				</van-cell-group>
				<van-cell-group inset class="input-box">
					<van-field v-model="formdata.passWord" name="passWord" type="password"
						:rules="[{ required: true, message: '请填写密码' }]" label="密码" placeholder="请输入密码" />
				</van-cell-group>
				<view style="display: flex;justify-content: center;">
					<van-button class="gologin" type="primary" native-type="submit" :disabled="lodding"
						:style="{ opacity: !lodding ? 1 : 0.5 }">
						<span class="loader" v-if="lodding"></span>{{ lodding ? "登录中" : "登录" }}
					</van-button>
				</view>
			</van-form>
			<!-- <button @click="getWeChatCode">getWeChatCode</button> -->
		</view>
	</view>
</template>

<script>
	import {
		reactive,
		toRefs,
		onMounted
	} from 'vue'
	import loginApi from '@/api/login.js'
	import api from '../../api'
	export default {
		setup() {
			const data = reactive({
				title: 'Hello',
				formdata: {
					userName: '',
					passWord: '',
				},
				lodding: false,
				rulesName: [{
						required: true,
						message: '请输入手机号码'
					},
					{
						pattern: /^1[3-9]\d{9}$/,
						message: '手机号码格式错误'
					}
				],
				isWeixin: true
			})
			const gologin = (values) => {
				// console.log('submit', values);


				// setTimeout(()=> {

				// },1500)
				// loginApi.loginByOpenid({openid: 'ovfHc6eHxJ3ZOzoI9UXZ-aHTYRYc'})
				loginApi.login(data.formdata.userName, data.formdata.passWord).then(res => {
					uni.setStorageSync('token', res.data.token)
					uni.setStorageSync('userInfo', res.data)
					uni.showToast({
						title: '登录成功'
					})
					uni.reLaunch({
						url: '/pages/index/index'
					})
				})
			}
			// const isWechat = () => {
			// 	var ua = window.navigator.userAgent.toLowerCase();
			// 	if (ua.match(/micromessenger/i) == 'micromessenger') {
			// 		return true;
			// 	} else {
			// 		return false;
			// 	}
			// }
			/*微信登录相关  start*/
			//方法：用来判断是否是微信内置的浏览器
			const isWechat = () => {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			}
			//方法:用来提取code
			const getUrlCode = (name) => {
				console.log(location.href)
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
						''
					])[1]
					.replace(/\+/g, '%20')) || null
			}
			//检查浏览器地址栏中微信接口返回的code
			const checkWeChatCode = () => {
				let code = getUrlCode('code')
				uni.showToast({
					title: `微信code=${code}`
				})
				// if (code) {
				// 	getOpenidAndUserinfo(code)
				// }
			}
			//请求微信接口，用来获取code
			const getWeChatCode = () => {
				// let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				// let local = 'https%3A%2F%2Fpayhub.jinmi.lengshan.com.cn%2Fwechat%2Fmp%2Fcallback'; //获取当前页面地址作为回调地址
				let local = 'https://gasmate.h5.jinmi.lengshan.com.cn'; //获取当前页面地址作为回调地址
				let appid = 'wxd097a41dbfb4743b'
				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				// 
				// console.log("https://wechat.lengshan.com.cn/open/oauth?appid=" +
				// 	appid +
				// 	"&scope=snsapi_base&return_url=" +
				// 	local)
				// https://wechat.lengshan.com.cn/open/oauth?appid=wxd097a41dbfb4743b&scope=snsapi_base&return_url=https://gasmate.h5.jinmi.lengshan.com.cn
				window.location.href =
					"https://wechat.lengshan.com.cn/open/oauth?appid=" +
					appid +
					"&scope=snsapi_base&return_url=" +
					local;
				// window.location.href = 'https://wechat.lengshan.com.cn/open/oauth?appid=wxd097a41dbfb4743b&scope=snsapi_base&return_url=https%3A%2F%2Fpayhub.jinmi.lengshan.com.cn%2Fwechat%2Fmp%2Fcallback';
			}
			//把code传递给后台接口，静默登录
			const getOpenidAndUserinfo = (code) => {
				// this.$http({
				// 	url: 'api/login',
				// 	data: {
				// 		code: code
				// 	}
				// }).then((res) => {
				// 	console.log(res)
				// 	if (res.code != 0) {
				// 		uni.showToast({
				// 			title: res.msg,
				// 			duration: 3000,
				// 			icon: 'none'
				// 		});
				// 		return
				// 	} else {
				// 		this.afterLogin(res)
				// 	}
				// })
			}
			/*微信登录相关  end*/
			const afterLogin = (res) => {
				let user = res.data.user
				uni.setStorageSync('token', res.data.token);
				let u = {
					avatar: user.avatar ? user.avatar : this.avatar,
					mobile: user.mobile,
					nickname: user.nickname ? user.nickname : '土肥圆'
				}
				uni.setStorage({
					key: 'u',
					data: u,
					success: () => {

						let url = uni.getStorageSync('redirect')
						uni.reLaunch({
							url: url ? url : '/pages/index'
						})
					}
				});
			}
			// 获取openid
			const getOpenId = () => {
				// 创建 URL 对象
				let urlObj = new URL(window.location.href);
				// 获取 URLSearchParams 对象
				let searchParams = urlObj.searchParams;
				// 获取 openid 参数的值
				let openid = searchParams.get('openid');
				// 输出 openid 参数的值
				return openid;
			}
			onMounted(() => {
				console.log(isWechat(), '打开客户端')
				// data.isWeixin = true;
				// return
				if (uni.getStorageSync('token')) {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				} else {
					if (isWechat()) {
						if (window.location.href.indexOf('openid') != -1) {
							loginApi.loginByOpenid({
								openid: getOpenId()
							}).then(res => {
								if(res.data) {
									uni.setStorageSync('token', res.data.token)
									uni.setStorageSync('userInfo', res.data)
									// uni.showToast({
									// 	title: '登录成功'
									// })
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}else {
									data.isWeixin = true;
									uni.showToast({
										title: '用户信息为空',
										icon: 'none'
									})
								}
								
							})
						} else {
							getWeChatCode()
						}
						// checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
					} else {
						data.isWeixin = true;
					}
				}

			})
			return {
				...toRefs(data),
				gologin,
				getWeChatCode
			}
		}
	}
</script>

<style lang="less" scoped>
	.content {
		width: 100%;
		height: 100vh;
		overflow: hidden;

		.title {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 80rpx;

			image {
				width: 200rpx;
				height: 200rpx;
				margin-right: 40rpx;
			}

			.title-rt {
				p {
					margin-top: 40rpx;
				}
			}
		}

		.form-input {
			margin-top: 80rpx;

			.input-box {
				margin-top: 30rpx;
				box-shadow: 0 0 30rpx 0 rgba(0, 0, 0, .1);
			}
		}
	}

	.gologin {
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgb(0, 82, 204);
		color: #fff;
		margin-top: 60rpx;
		border: 0;
		width: 96%;
		border-radius: 0.4415rem;
		padding: 0.2831rem;
	}

	.loader {
		display: inline-block;
		border: 4px solid #f3f3f3;
		border-top: 4px solid #3498db;
		border-radius: 50%;
		width: 20px;
		height: 20px;
		animation: spin 1s linear infinite;
		margin-right: 0.1932rem;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>